import React, { useContext, useState } from 'react'
import { nanoid } from 'nanoid'
import { TodoContext } from '../../todoContext'

const Header = () => {
    const { list, setList } = useContext(TodoContext)
    const [title, setTitle] = useState("");
    const addItem = () => {
        if (!title) {
            return alert("添加内容不能为空！");
        }
        const todo = { title, id: nanoid(4), done: false };
        setList(list => list = [todo, ...list])
        setTitle('');
    }
    const changeTitle = (e) => {
        var title = e.currentTarget.value.trim();
        if (!title) {
            return false;
        }
        setTitle(title);
    }
    const keySubmit = (e) => {
        if (e.keyCode == 13) {
            addItem();
        }
    }
    return (
        <div className='header-wrapper' onKeyUp={keySubmit}>
            <input onChange={changeTitle} value={title} />
            <button className='btn' onClick={addItem}>添加</button>
        </div>
    )
}

export default Header
